package com.longtop.perform.zb.system.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.longtop.framework.base.BaseService;
import com.longtop.framework.common.Constant;
import com.longtop.framework.common.QueryConditions;
import com.longtop.framework.common.QueryResult;
import com.longtop.framework.security.BaseCheckedException;
import com.longtop.framework.security.SessionObject;
import com.longtop.framework.util.StringUtil;
import com.longtop.intelliweb.view.Record;
import com.longtop.perform.zb.system.model.TZbSystemClass;
import com.longtop.perform.zb.system.model.TZbSystemClassMx;

public class SystemClassService extends BaseService {

	public static final String BEAN_ID = "systemClassService";

	/**
	 * 依据条件，读取代码类别列表
	 * 
	 * @param queryConditions
	 *            查询条件
	 * @param pageNo
	 *            查询结果的起始页码。
	 * @param pageSize
	 *            查询结果的最大行数。如果不需要，则设置为-1
	 * @return
	 */
	public QueryResult loadSystemClass(QueryConditions queryConditions, int pageNo, int pageSize) {

		String hql = "from TZbSystemClass";
		String[] propertyNames = null;
		String[] operators = null;
		Object[] values = null;

		String orderBy = "";

		if (queryConditions != null) {
			propertyNames = StringUtil.listToStrArray(queryConditions.getPropertyNames());
			operators = StringUtil.listToStrArray(queryConditions.getOperators());
			List valuesList = queryConditions.getValues();
			values = valuesList == null || valuesList.size() == 0 ? null : valuesList.toArray();
		}

		int offset = (pageNo - 1) * pageSize;

		// 执行查询
		Object[] result = this.query(hql, propertyNames, operators, values, offset, pageSize, true, orderBy, null, null);

		return new QueryResult((List) result[0], result[1] != null ? ((Integer) result[1]).intValue() : 0);
	}

	/**
	 * 保存、修改一起做！
	 * 
	 * @param changeMap
	 *            对象列表，有三个值，删除主键列表、更新bean的列表、新增bean的列表
	 * @param sessionObject
	 * @return 操作成功受影响的记录数，有三个值，插入成功的记录数、更新成功的记录数、删除成功的记录数
	 * @throws BaseCheckedException
	 */
	public Integer[] saveSystemClass(Map changeMap, SessionObject sessionObject, List zbTeamIndexList) throws BaseCheckedException {

		// 插入成功的记录数、更新成功的记录数、删除成功的记录数
		// 插入成功的记录数、更新成功的记录数、删除成功的记录数
		int insertCount = 0;
		int updateCount = 0;
		int deleteCount = 0;

		// 删除主键列表、更新bean的列表、新增bean的列表
		List insertBeanList = (ArrayList) changeMap.get(Constant.INSERT_BEAN_LIST);
		List updateBeanList = (ArrayList) changeMap.get(Constant.UPDATE_BEAN_LIST);
		String idList = (String) changeMap.get(Constant.ID_LIST);
		TZbSystemClass zbSystemClass;
		Iterator iterator;

		// 批量插入记录
		if (insertBeanList.size() > 0) {
			iterator = insertBeanList.iterator();
			while (iterator.hasNext()) {
				zbSystemClass = (TZbSystemClass) iterator.next();

				zbSystemClass.setClassId(zbSystemClass.getParentClassId() + "|" + zbSystemClass.getClassId());
				// 校验指标集合Id是否重复。
				if (isExistClassId(zbSystemClass.getClassId())) {
					throw new BaseCheckedException("", "保存失败,指标类ID【" + zbSystemClass.getClassId() + "】已经存在!");
				}
				
				if (isExistClassName(zbSystemClass.getClassName(),zbSystemClass.getParentClassId())) {
					throw new BaseCheckedException("", "保存失败,指标类名称【" + zbSystemClass.getClassName() + "】已经存在!");
				}
				super.save(zbSystemClass);
				insertCount++;
				String classId = zbSystemClass.getClassId();
				for (int i = 0; i < zbTeamIndexList.size(); i++) {
					TZbSystemClassMx zbSystemClassIndex = new TZbSystemClassMx();
					Record record = (Record) zbTeamIndexList.get(i);
					if (record.getState() == 3) {
					} else {
						String indexId = record.getValue("indexId").toString();
						zbSystemClassIndex.setIndexId(indexId);
						zbSystemClassIndex.setClassId(classId);
						super.save(zbSystemClassIndex);
					}
				}
			}
		}

		// 批量更新记录
		if (updateBeanList.size() > 0) {
			iterator = updateBeanList.iterator();
			while (iterator.hasNext()) {
				zbSystemClass = (TZbSystemClass) iterator.next();
				super.update(zbSystemClass);
				updateCount++;
				// 删除关联
				String classId = zbSystemClass.getClassId();
				String sql = "delete from TZbSystemClassMx where classId ='" + classId + "'";
				super.batchUpdate(sql);
				for (int i = 0; i < zbTeamIndexList.size(); i++) {
					TZbSystemClassMx zbSystemClassIndex = new TZbSystemClassMx();
					Record record = (Record) zbTeamIndexList.get(i);
					if (record.getState() == 3) {
					} else {
						String indexId = record.getValue("indexId").toString();
						zbSystemClassIndex.setIndexId(indexId);
						zbSystemClassIndex.setClassId(classId);
						super.save(zbSystemClassIndex);
					}
				}
			}
		}
		return new Integer[] { new Integer(insertCount), new Integer(updateCount), new Integer(deleteCount) };
	}

	/**
	 * 验证此 指标分类名称 是否存在
	 * 
	 * @param menuId
	 * @return
	 */
	private boolean isExistClassName(String className,String parentClassId) {
		boolean flag = false;
		List list = this.queryAll("from TZbSystemClass where className='" + className + "' and parentClassId='"+parentClassId+"'");

		if (list.size() > 0)
			flag = true;

		return flag;
	}
	
	/**
	 * 验证此 指标分类ID 是否存在
	 * 
	 * @param menuId
	 * @return
	 */
	private boolean isExistClassId(String classId) {
		boolean flag = false;
		List list = this.queryAll("from TZbSystemClass where classId='" + classId + "'");

		if (list.size() > 0)
			flag = true;

		return flag;
	}

	/**
	 * 删除指标
	 * 
	 * @param userId
	 * @throws BaseCheckedException
	 */
	public void deleteSystemClass(String classId) throws BaseCheckedException {
		// 保存
		List lists = this.queryAll("from TZbSystemClass where parentClassId='" + classId + "'");
		if (lists.size() > 0)
			throw new BaseCheckedException("", "删除失败,指标类下还有子指标类存在,不能删除!");
		String sql = "delete from TZbSystemClassMx where classId ='" + classId + "'";
		super.batchUpdate(sql);
		super.delete(TZbSystemClass.class, classId);
	}

}